package 事务操作;

import java.sql.*;
import java.util.Scanner;

/**
 * 转账:A给B转？？？元
 */
public class Transaction3 {
    public static void main(String[] args) throws SQLException {
        String fkf = null;
        String skf = null;
        int rmb = 0;
        //接收用户输入 Scanner
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入本次的转账金额");
        rmb = sc.nextInt();
        System.out.println("请输入付款方id:");
        fkf = sc.next();
        System.out.println("请输入收款方id:");
        skf = sc.next();
        System.out.println("正在转账" + rmb + "元");
        String url = "jdbc:mysql://localhost:3306/db_jdbc_demo" +
                "?characterEncoding=utf8&useSSL=false&serverTimezone=UTC";
        String user = "root";
        String pass = "1234";
        Connection conn = null;
        PreparedStatement pstmt = null;
        //将Statement换成高级版

        //ResultSet省略，因为Update没有结果集

        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,user,pass);
//            String sql1 = "update t_account set money = money - "+rmb+" where id = "+fkf;
            String sql1 = "update t_account set money = money - ? where id = ?";
            String sql2 = "update t_account set money = money + ? where id = ?";
//            String sql2 = "update t_account set money = money + "+rmb+" where id = "+skf;
            // 开启事务
            conn.setAutoCommit(false);
            pstmt = conn.prepareStatement(sql1); //预编译的Statement对象(高级版)
            //将SQL中的？换成具体数值
            pstmt.setInt(1,rmb);
            pstmt.setString(2,fkf);
            int i = pstmt.executeUpdate();
//            int x = 5/0;
            pstmt = conn.prepareStatement(sql2); //预编译的Statement对象(高级版)
            //将SQL中的？换成具体数值
            pstmt.setInt(1,rmb);
            pstmt.setString(2,skf);
            int j = pstmt.executeUpdate();
            if (i+j==2){
                System.out.println("转账成功!");
                conn.commit();
            }else {
                System.out.println("转账失败!");
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.out.println("转账出现异常!");
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        finally {
            pstmt.close();
            conn.commit();

        }
    }
}